import {
  ConfigProvider,
  Image,
  Tabs,
  Swiper,
  Loading,
  Navbar,
  SafeArea,
} from "@taroify/core";
import { View } from "@tarojs/components";
import TuijianIcon from "@/assets/images/tuijian.png";
import { LocationOutlined, UserOutlined, PhoneOutlined } from "@taroify/icons";
import { useEffect, useState } from "react";
import OneIcon from "@/assets/images/1.png";
import TowIcon from "@/assets/images/2.png";
import ThreeIcon from "@/assets/images/3.png";
import { RootState } from "@/store";
import { useDispatch, useSelector } from "react-redux";
import { requestPOST } from "@/request";
import Taro, { useDidShow } from "@tarojs/taro";
import LogoPng from "@/assets/images/logo.png";
import { setUserInfo } from "@/store/reducers/userInfo";

export default function Home() {
  const accountType = useSelector(
    (state: RootState) => state.userInfo.accountType
  );
  const offlineStores = useSelector(
    (state: RootState) => state.userInfo.offlineStores
  );
  const shopOwnerInfo = useSelector(
    (state: RootState) => state.userInfo.shopOwnerInfo
  );
  const merchantInfo2 = useSelector(
    (state: RootState) => state.userInfo.merchantInfo
  );
  const [merchantInfo, setMerchantInfo] = useState<any>({});
  const baseUrl = process.env.TARO_APP_API;
  const [value, setValue] = useState("recommended");
  const [productList, setProductList] = useState<any>([]);
  const [productType, setProductType] = useState<any>([]);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  const getProductList = () => {
    setLoading(true);
    requestPOST("product/getProductListByParam", {
      isPage: 1,
      pageNumIndex: 1,
      pageSizeIndex: 10,
      productIsRecommended: 1,
    })
      .then((res: any) => {
        setProductList([...res.vos]);
        console.log(res);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  const getProductListOfType = (typeId = "") => {
    setLoading(true);
    requestPOST("product/getProductListByParam", {
      isPage: 1,
      pageNumIndex: 1,
      pageSizeIndex: 10,
      typeId: typeId,
    })
      .then((res: any) => {
        setProductList([...res.vos]);
        console.log(res);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const getProductType = () => {
    requestPOST("product/getProductTypeList", {
      params: {
        searchProductList: false,
        productListParams: {
          isPage: false,
        },
      },
    }).then((res: any) => {
      setProductType([...res]);
      console.log(res);
    });
  };

  const handleChange = (value) => {
    setValue(value);
    if (value === "recommended") {
      getProductList();
    } else if (value === "all") {
      getProductListOfType("");
    } else {
      getProductListOfType(value);
    }
  };

  const getBindMerchantInfo = () => {
    requestPOST("customer/getBindMerchantInfo").then((res: any) => {
      setMerchantInfo({ ...res });
    });
  };

  const getUserInfo = () => {
    if (accountType == 1) {
      requestPOST("merchants/getUserInfo").then((res: any) => {
        res.token = Taro.getStorageSync("token");
        Taro.setStorageSync("userInfo", res);
        dispatch(setUserInfo(res));
      });
    } else {
      requestPOST("customer/getCustomerInfo").then((res: any) => {
        res.token = Taro.getStorageSync("token");
        Taro.setStorageSync("userInfo", res);
        dispatch(setUserInfo(res));
      });
    }
  };

  useEffect(() => {
    getProductList();
    getProductType();
    getUserInfo();

    if (accountType === 2) {
      getBindMerchantInfo();
    } else {
      setMerchantInfo({ ...merchantInfo2 });
    }
  }, []);

  useDidShow(() => {
    if (accountType === 2) {
      getBindMerchantInfo();
    } else {
      setMerchantInfo({ ...merchantInfo2 });
    }
  });

  return (
    <View className="taroContainer">
      <Navbar
        fixed
        nativeSafeTop
        safeArea="top"
        className="navBar"
        style={{ background: "#e3f3fe" }}
        placeholder={true}
      >
        <Navbar.Title style={{ maxWidth: "100%" }}>
          <View
            style={{
              display: "flex",
              alignItems: "center",
              width: "100vw",
              justifyContent: "center",
              position: "relative",
              fontSize: "28rpx",
              fontWeight: "normal",
            }}
          >
            <View style={{ position: "absolute", left: 20 }}>
              {merchantInfo.merchantName}
            </View>
            <View>首页</View>
          </View>
        </Navbar.Title>
      </Navbar>
      <Swiper
        style={{ height: "600rpx" }}
        autoplay={4000}
        lazyRender
        stopPropagation={false}
      >
        <Swiper.Indicator />
        {merchantInfo.merchantImages?.split(",").map((item, index) => (
          <Swiper.Item key={index}>
            <Image
              src={baseUrl + item}
              width="100%"
              height={600}
              mode="aspectFill"
            />
          </Swiper.Item>
        ))}
      </Swiper>
      {accountType === 1 && offlineStores.merchantLogo && (
        <View style={{ padding: "24rpx" }}>
          <View
            style={{
              padding: "30rpx 27rpx",
              boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
              borderRadius: "14rpx",
              background: "#fff",
            }}
          >
            <View
              style={{
                display: "flex",
                alignItems: "center",
                gap: "18rpx",
                width: "100%",
              }}
            >
              <Image
                shape="circle"
                src={
                  offlineStores.merchantLogo
                    ? baseUrl + offlineStores.merchantLogo
                    : merchantInfo.merchantImage?.split(",")[0]
                }
                width={70}
                height={70}
              />
              <View
                style={{
                  fontWeight: "bold",
                  fontSize: "33rpx",
                  color: "#222222",
                }}
              >
                {merchantInfo.merchantName}
              </View>
            </View>
            <View
              style={{
                display: "flex",
                flexDirection: "column",
                gap: "15rpx",
                marginTop: "50rpx",
              }}
            >
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <LocationOutlined />
                <View style={{ fontSize: "28rpx", color: "#666666" }}>
                  {offlineStores.merchantAddress}
                </View>
              </View>
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <UserOutlined />
                <View style={{ fontSize: "28rpx", color: "#666666" }}>
                  {offlineStores.merchantUserName}
                </View>
              </View>
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <PhoneOutlined />
                <View style={{ fontSize: "28rpx", color: "#666666" }}>
                  {offlineStores.merchantPhone}
                </View>
              </View>
              <View
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "20rpx",
                  fontSize: "28rpx",
                  color: "#666666",
                }}
              >
                <View>营业时间:</View>
                <View>{merchantInfo.merchantsBusinessHours}</View>
              </View>
            </View>
          </View>
        </View>
      )}

      {accountType === 2 && (
        <View style={{ padding: "24rpx" }}>
          <View
            style={{
              padding: "70rpx 27rpx",
              boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
              borderRadius: "14rpx",
              background: "#fff",
            }}
          >
            <View
              style={{
                display: "flex",
                alignItems: "center",
                gap: "18rpx",
                width: "100%",
              }}
            >
              <Image
                shape="circle"
                src={
                  merchantInfo.merchantLogo
                    ? baseUrl + merchantInfo.merchantLogo
                    : LogoPng
                }
                width={70}
                height={70}
              />
              <View
                style={{
                  fontWeight: "bold",
                  fontSize: "33rpx",
                  color: "#222222",
                }}
              >
                {merchantInfo.merchantName}
              </View>
            </View>
            <View
              style={{
                display: "flex",
                flexDirection: "column",
                gap: "15rpx",
                marginTop: "50rpx",
              }}
            >
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <LocationOutlined />
                <View style={{ fontSize: "26rpx", color: "#666666" }}>
                  {merchantInfo.merchantAddress}
                </View>
              </View>
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <UserOutlined />
                <View style={{ fontSize: "26rpx", color: "#666666" }}>
                  {merchantInfo.merchantName}
                </View>
              </View>
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <PhoneOutlined />
                <View style={{ fontSize: "26rpx", color: "#666666" }}>
                  {merchantInfo.merchantPhone}
                </View>
              </View>
            </View>
          </View>
        </View>
      )}

      {/* {accountType != 1 && (
        <Image src="https://dummyimage.com/750x222" width={750} height={222} />
      )} */}

      <View style={{ padding: "0 24rpx 24rpx 24rpx" }}>
        <View
          style={{
            width: "100%",
            height: "362rpx",
            display: "grid",
            gridTemplateAreas: "'a b' 'a c'",
            gridTemplateColumns: "repeat(2,1fr)",
            gridTemplateRows: "repeat(2,1fr)",
            gap: "14rpx",
            marginTop: "43rpx",
          }}
        >
          <View
            onClick={() =>
              Taro.navigateTo({ url: "/packages/activity/index?value=0" })
            }
            style={{
              gridArea: "a",
              boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
              borderRadius: "14rpx",
            }}
          >
            <Image src={OneIcon} width="100%" height="100%" />
          </View>
          <View
            onClick={() =>
              Taro.navigateTo({ url: "/packages/activity/index?value=1" })
            }
            style={{
              gridArea: "b",
              boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
              borderRadius: "14rpx",
            }}
          >
            <Image src={ThreeIcon} width="100%" height="100%" />
          </View>
          <View
            onClick={() =>
              Taro.navigateTo({ url: "/packages/activity/index?value=2" })
            }
            style={{
              gridArea: "c",
              boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
              borderRadius: "14rpx",
            }}
          >
            <Image src={TowIcon} width="100%" height="100%" />
          </View>
        </View>
        {(accountType != 1 || !offlineStores.merchantLogo) && (
          <View style={{ marginTop: "40rpx" }}>
            <ConfigProvider
              theme={{
                tabsNavBackgroundColor: "#f6f6f6",
              }}
            >
              <Tabs
                className="customTabs"
                value={value}
                onChange={(value) => handleChange(value)}
                ellipsis={false}
              >
                <Tabs.TabPane
                  value="recommended"
                  title={
                    <View style={{ display: "flex", gap: "10rpx" }}>
                      <Image src={TuijianIcon} width={25} height={25} />
                      <View>今日推荐</View>
                    </View>
                  }
                ></Tabs.TabPane>
                <Tabs.TabPane value="all" title="全部商品"></Tabs.TabPane>
                {productType.map((item) => (
                  <Tabs.TabPane
                    key={item.id}
                    value={item.id}
                    title={item.typeName}
                  ></Tabs.TabPane>
                ))}
              </Tabs>
            </ConfigProvider>

            {loading ? (
              <View style={{ textAlign: "center", padding: "40rpx 0" }}>
                <Loading>加载中...</Loading>
              </View>
            ) : (
              <View
                style={{
                  marginTop: "40rpx",
                  display: "flex",
                  flexDirection: "column",
                  gap: "20rpx",
                }}
              >
                {productList.map((item) => (
                  <View
                    key={item.id}
                    style={{
                      borderRadius: "14rpx",
                      boxShadow: "0rpx 1rpx 9rpx 0rpx rgba(59,59,59,0.19)",
                      overflow: "hidden",
                      display: "flex",
                      backgroundColor: "#fff",
                    }}
                    onClick={() =>
                      Taro.navigateTo({
                        url: `/packages/goodsDetail/index?id=${item.id}`,
                      })
                    }
                  >
                    <Image
                      src={baseUrl + item.productImage[0]}
                      width={250}
                      height={250}
                    />
                    <View
                      style={{
                        padding: "26rpx",
                        display: "flex",
                        flexDirection: "column",
                      }}
                    >
                      <View
                        style={{
                          gap: "20rpx",
                        }}
                      >
                        <View
                          style={{
                            background: "#FF4444",
                            borderRadius: "7rpx",
                            color: "#FFFEFE",
                            fontSize: "22rpx",
                            height: "33rpx",
                            lineHeight: "33rpx",
                            width: "64rpx",
                            textAlign: "center",
                            display: "inline-block",
                            marginRight: "10rpx",
                          }}
                        >
                          推荐
                        </View>
                        <View
                          style={{
                            fontSize: "25rpx",
                            color: "#333",
                            display: "inline",
                          }}
                        >
                          {item.productName}
                        </View>
                      </View>
                      <View
                        style={{
                          display: "flex",
                          alignItems: "baseline",
                          marginTop: "auto",
                        }}
                      >
                        <View
                          style={{
                            fontWeight: "bold",
                            fontSize: "21rpx",
                            color: "#f90000",
                          }}
                        >
                          ￥
                        </View>
                        <View
                          style={{
                            fontWeight: "bold",
                            fontSize: "33rpx",
                            color: "#f90000",
                          }}
                        >
                          {item.currentPrice}
                        </View>
                        <View
                          style={{
                            fontSize: "21rpx",
                            color: "#AAAAAA",
                            textDecorationLine: "line-through",
                            marginLeft: "15rpx",
                          }}
                        >
                          ￥{item.originalPrice}
                        </View>
                      </View>
                      <View style={{ fontSize: "21rpx", color: "#999999" }}>
                        已售{item.salesVolume || 0}
                      </View>
                    </View>
                  </View>
                ))}
              </View>
            )}
          </View>
        )}
      </View>
    </View>
  );
}
